<template>
  <PageContainer title="公告通知">
    <div class="notice-list-container">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索公告标题"
          clearable
          style="width: 300px"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          prefix-icon="el-icon-search"
        />
      </div>

      <!-- 公告列表表格 -->
      <div class="table-section" style="margin-top: 20px">
        <el-table
          :data="noticeList"
          :loading="loading"
          border
          stripe
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="(scope) => scope.row ? 'table-row-hover' : ''"
        >
          <el-table-column
            prop="title"
            label="公告标题"
            align="left"
            min-width="250"
          >
            <template #default="scope">
              <span class="title-text" :title="scope.row.title">
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="tag"
            label="公告标签"
            align="center"
            width="140"
          >
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.tag)">
                {{ scope.row.tag || '无标签' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="publishTime"
            label="发布时间"
            align="center"
            width="180"
            sortable
            :sort-method="(a, b) => new Date(b.publishTime) - new Date(a.publishTime)"
          >
            <template #default="scope">
              {{ formatTime(scope.row.publishTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorName"
            label="创建人"
            align="center"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.creatorName || '未知' }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row, $event)"
                :loading="detailLoading && currentNoticeId === scope.row.id"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && noticeList.length === 0"
          description="暂无作家助手相关公告"
          style="margin: 80px 0"
        >
          <template #image>
            <img
              src="@/assets/avatar.jpg"
              alt="无公告"
              style="width: 180px; height: 180px"
            />
          </template>
        </el-empty>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-section" style="margin-top: 16px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>

      <!-- 公告详情抽屉（核心新增） -->
      <el-drawer
        v-model="drawerVisible"
        title="公告详情"
        direction="rtl"
        size="50%"
        :before-close="handleDrawerClose"
        :loading="detailLoading"
      >
        <div class="notice-detail" v-if="noticeDetail">
          <!-- 详情头部：标题+标签 -->
          <div class="detail-header">
            <h3 class="detail-title">{{ noticeDetail.title }}</h3>
            <el-tag :type="getTagType(noticeDetail.tag)" class="detail-tag">
              {{ noticeDetail.tag || '无标签' }}
            </el-tag>
          </div>

          <!-- 详情meta信息：发布时间+创建人 -->
          <div class="detail-meta">
            <span class="meta-item">发布时间：{{ formatTime(noticeDetail.publishTime) }}</span>
            <span class="meta-item">创建人：{{ noticeDetail.creatorName || '未知管理员' }}</span>
          </div>

          <!-- 详情内容（支持换行显示） -->
          <div class="detail-content">
            <p v-if="noticeDetail.content" v-html="formatContent(noticeDetail.content)"></p>
            <p v-else class="empty-content">暂无公告内容</p>
          </div>

          <!-- 已读按钮（底部靠右） -->
          <div class="detail-footer">
            <el-button
              type="primary"
              @click="handleMarkRead"
              :loading="markReadLoading"
            >
              标记为已读
            </el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElTag, ElDrawer } from 'element-plus';
import dayjs from 'dayjs';
import PageContainer from '@/components/PageContainer.vue';
// 导入列表和详情接口
import { getNoticeList,getNoticeInfo } from '@/api/user';
// （可选）导入已读接口，若后端有则替换占位
// import { markNoticeRead } from '@/api/user';


// ---------------------- 原有变量 ----------------------
// 搜索参数
const searchKeyword = ref('');
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
// 列表数据与状态
const noticeList = ref([]);
const loading = ref(false);

// ---------------------- 新增抽屉/详情变量 ----------------------
const drawerVisible = ref(false); // 抽屉显示状态
const noticeDetail = ref(null); // 单个公告详情数据
const detailLoading = ref(false); // 详情加载状态
const markReadLoading = ref(false); // 已读按钮加载状态
const currentNoticeId = ref(''); // 当前查看的公告ID（用于加载状态匹配）

// ---------------------- 原有列表加载逻辑 ----------------------
const loadAdminNoticeList = async () => {
  try {
    loading.value = true;
    console.log('=== 开始请求公告列表 ===');
    console.log('请求参数:', {
      page: currentPage.value,
      limit: pageSize.value,
      object: '作家助手',
      keyword: searchKeyword.value.trim()
    });

    const result = await getNoticeList({
      page: currentPage.value,
      limit: pageSize.value,
      object: '作家助手',
      keyword: searchKeyword.value.trim()
    });

    console.log('接口响应（完整Axios对象）:', result);
    const businessData = result.data;
    console.log('业务数据:', businessData);

    if (businessData.code === '0000') {
      noticeList.value = businessData.data.list || [];
      totalCount.value = businessData.data.pagination?.total || 0;
      console.log('公告列表数据:', noticeList.value);
      console.log('总条数:', totalCount.value);
    } else {
      ElMessage.error(businessData.msg || '获取作家助手公告失败');
      console.error('接口业务错误:', businessData.msg || '未知错误');
    }
  } catch (error) {
    ElMessage.error('网络异常，请重试');
    console.error('请求公告列表异常:', error);
    console.error('异常详情:', error.message, error.response?.data);
  } finally {
    loading.value = false;
    console.log('=== 请求公告列表结束 ===');
  }
};

// ---------------------- 新增：获取单个公告详情 ----------------------
const fetchNoticeDetail = async (noticeId) => {
  try {
    currentNoticeId.value = noticeId;
    detailLoading.value = true;
    console.log('=== 开始请求公告详情 ===');
    console.log('请求参数（公告ID）:', noticeId);

    // 调用详情接口：后端用query传id，所以params里带id
    const result = await getNoticeInfo({ id: noticeId });
    console.log('详情接口响应:', result);
    const businessData = result.data;

    if (businessData.code === '0000') {
      // 补充创建人信息（详情接口没返回时，从列表数据取）
      const listItem = noticeList.value.find(item => item.id === noticeId);
      noticeDetail.value = {
        ...businessData.data,
        creatorName: listItem?.creatorName || '未知管理员' // 对齐列表的创建人昵称
      };
      drawerVisible.value = true; // 打开抽屉
    } else if (businessData.code === '2004') {
      ElMessage.warning('公告不存在或无权限查看');
    } else if (businessData.code === '2005') {
      ElMessage.warning('公告ID格式错误');
    } else {
      ElMessage.error(businessData.msg || '获取公告详情失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，无法加载详情');
    console.error('请求公告详情异常:', error);
  } finally {
    detailLoading.value = false;
    console.log('=== 请求公告详情结束 ===');
  }
};

// ---------------------- 新增：标记已读（可对接后端接口） ----------------------
const handleMarkRead = async () => {
  try {
    markReadLoading.value = true;
    const noticeId = noticeDetail.value.id;
    console.log('=== 标记公告已读 ===');
    console.log('公告ID:', noticeId);

    // ---------------------- 此处对接后端已读接口（示例） ----------------------
    // 若后端有已读接口，替换下方占位逻辑
    // const result = await markNoticeRead({ noticeId });
    // if (result.data.code === '0000') {
    //   ElMessage.success('已成功标记为已读');
    //   drawerVisible.value = false; // 标记后关闭抽屉
    // } else {
    //   ElMessage.error(result.data.msg || '标记已读失败');
    // }

    // 占位逻辑：无接口时仅提示
    ElMessage.success('已成功标记为已读');
    drawerVisible.value = false;

  } catch (error) {
    ElMessage.error('标记已读失败，请重试');
    console.error('标记公告已读异常:', error);
  } finally {
    markReadLoading.value = false;
  }
};

// ---------------------- 新增：抽屉关闭逻辑 ----------------------
const handleDrawerClose = () => {
  // 关闭抽屉时重置详情数据
  noticeDetail.value = null;
  currentNoticeId.value = '';
  drawerVisible.value = false;
};

// ---------------------- 原有事件逻辑改造 ----------------------
// 搜索事件（不变）
const handleSearch = () => {
  console.log('搜索关键词变化:', searchKeyword.value);
  currentPage.value = 1;
  loadAdminNoticeList();
};

// 分页事件（不变）
const handleSizeChange = (val) => {
  console.log('每页条数变化:', val);
  pageSize.value = val;
  currentPage.value = 1;
  loadAdminNoticeList();
};
const handleCurrentChange = (val) => {
  console.log('页码变化:', val);
  currentPage.value = val;
  loadAdminNoticeList();
};

// 标签类型映射（不变）
const getTagType = (tag) => {
  const tagTypeMap = {
    '系统通知': 'success',
    '紧急通知': 'danger',
    '活动提醒': 'primary',
    '其他': 'info'
  };
  return tagTypeMap[tag] || 'default';
};

// 时间格式化（不变）
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '未记录';
};

// 行点击：改为打开抽屉（原跳转逻辑注释）
const handleRowClick = (row) => {
  console.log('点击公告行，ID:', row.id);
  // router.push(`/system/notice-detail/${row.id}`); // 移除跳转
  fetchNoticeDetail(row.id); // 打开抽屉详情
};

// 查看详情按钮：改为打开抽屉（原跳转逻辑注释）
const handleViewDetail = (row, event) => {
  event.stopPropagation(); // 阻止行点击事件冒泡
  console.log('点击查看详情按钮，ID:', row.id);
  // router.push(`/system/notice-detail/${row.id}`); // 移除跳转
  fetchNoticeDetail(row.id); // 打开抽屉详情
};

// 新增：格式化详情内容（支持换行）
const formatContent = (content) => {
  // 将\n替换为<br>，让换行在HTML中生效
  return content.replace(/\n/g, '<br>');
};

// 页面挂载（不变）
onMounted(() => {
  console.log('组件挂载，开始加载公告列表');
  loadAdminNoticeList();
});
</script>

<style lang="scss" scoped>
// 原有样式不变
.notice-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}
.search-section {
  padding: 8px 0;
  border-bottom: 1px solid #f2f2f2;
}
::v-deep .table-row-hover {
  &:hover > td {
    background-color: #f8f9fa !important;
    cursor: pointer;
  }
}
.title-text {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #303133;
  &:hover {
    color: #409eff;
  }
}
.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}

// ---------------------- 新增：抽屉详情样式 ----------------------
.notice-detail {
  padding: 16px 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .detail-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  .detail-tag {
    margin-top: 4px;
  }
}
.detail-meta {
  display: flex;
  gap: 24px;
  color: #606266;
  font-size: 14px;
  .meta-item {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}
.detail-content {
  flex: 1;
  color: #303133;
  line-height: 1.8;
  font-size: 14px;
  .empty-content {
    color: #909399;
    text-align: center;
    padding: 20px 0;
  }
  p {
    margin: 0 0 16px 0;
  }
}
.detail-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f2f2f2;
}

// 响应式适配
@media (max-width: 768px) {
  .search-section .el-input {
    width: 100% !important;
  }
  ::v-deep .el-table__fixed-right {
    right: 0 !important;
  }
  // 小屏幕抽屉宽度调整为80%
  ::v-deep .el-drawer.rtl {
    width: 80% !important;
  }
}
</style>